<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class HomeController extends CController {

    	public $layout='//layouts/column1';
	/**
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $menu=array();
	public $activemenu = null;
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs=array();
	public function init(){
		
		parent::init();
				
		Yii::app()->clientScript->registerCoreScript('jquery');
		$cs = Yii::app()->getClientScript();
		$addCart = Yii::app()->createUrl('/shoppingCart/create');
		$cs->registerScript(
				'add-cart-script',
				'function addCart(id){
					$.ajax({
						url: "'.$addCart.'",
						data: {pid:id},
						type: "post",
						success: function(result){
							if(result==1){
								reloadCart();
							}
						}
						
					})
				}',
				CClientScript::POS_HEAD
		);
		$reloadCart = Yii::app()->createUrl('/shoppingCart/reload');
		$cs->registerScript(
				'reload-cart-script',
				'function reloadCart(){
					$.ajax({
						url: "'.$reloadCart.'",
						success: function(result){
							if(result){
								$("#shopping-cart").html(result);
								alert("Đã thêm sản phẩm vào giỏ hàng!")
							}
						}
						
					})
				}',
				CClientScript::POS_HEAD
		);
	}
	/**
	 * @see CController::createUrl()
	 */
	public function createUrl($route,$params=array(),$ampersand='&')
	{
		if($route==='')
			$route=$this->getId().'/'.$this->getAction()->getId();
		else if(strpos($route,'/')===false)
			$route=$this->getId().'/'.$route;
		if($route[0]!=='/' && ($module=$this->getModule())!==null)
			$route=$module->getId().'/'.$route;
		if(Yii::app()->params['multilang'] && !isset($params['lang'])){
			if(isset($_GET['lang']) && $_GET['lang']!=''){
				$params['lang']=$_GET['lang'];
			}else{
				$params['lang']=Yii::app()->params['language_default'];
			}
		}
		return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
	}
	/**
	 * @see CController::createUrl()
	 */
	public function createUrlHome($params=array(),$ampersand='&')
	{
		$route = '/default/index';
		if($route==='')
			$route=$this->getId().'/'.$this->getAction()->getId();
		else if(strpos($route,'/')===false)
			$route=$this->getId().'/'.$route;
		if($route[0]!=='/' && ($module=$this->getModule())!==null)
			$route=$module->getId().'/'.$route;
		if(Yii::app()->params['multilang'] && !isset($params['lang'])){
			if(isset($_GET['lang']) && $_GET['lang']!=''){
				$params['lang']=$_GET['lang'];
			}else{
				$params['lang']=Yii::app()->params['language_default'];
			}
		}
		return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
	}
	/**
	 * Create Url Article
	 * @param Int $postId
	 * @param String $route
	 * @param array $params
	 * @param String $ampersand
	 */
	public function createUrlArticle($postId, $route='/post/read', $params=array(), $ampersand='&')
	{
		if($route==='')
			$route=$this->getId().'/'.$this->getAction()->getId();
		else if(strpos($route,'/')===false)
			$route=$this->getId().'/'.$route;
		if($route[0]!=='/' && ($module=$this->getModule())!==null)
			$route=$module->getId().'/'.$route;
		//get param for create url	
		$params['id'] 		= $postId;
					
		if(Yii::app()->params['multilang'] && !isset($params['lang'])){
			if(isset($_GET['lang']) && $_GET['lang']!=''){
				$params['lang']=$_GET['lang'];
			}else{
				$params['lang']=Yii::app()->params['language_default'];
			}
		}
		return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
	}
	/**
	 * Create Url Page Dynamic
	 * @param Int $postId
	 * @param String $route
	 * @param array $params
	 * @param String $ampersand
	 */
	public function createUrlPage($pageId, $route='/default/page', $params=array(), $ampersand='&')
	{
		if($route==='')
			$route=$this->getId().'/'.$this->getAction()->getId();
		else if(strpos($route,'/')===false)
			$route=$this->getId().'/'.$route;
		if($route[0]!=='/' && ($module=$this->getModule())!==null)
			$route=$module->getId().'/'.$route;
		
		//get param for create url
		$page = FrontendPagesModel::model()->published()->findByPk($pageId);
		$language = Yii::app()->language;
		$field = ($language=='vi')?'alias':'alias_'.$language;
		$params['alias'] 	= $page->{$field};
		if(Yii::app()->params['multilang'] && !isset($params['lang'])){
			if(isset($_GET['lang']) && $_GET['lang']!=''){
				$params['lang']=$_GET['lang'];
			}else{
				$params['lang']=Yii::app()->params['language_default'];
			}
		}
		return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
	}
	
	
	public function createUrlAskDetail($askId, $route='/ask/detail', $params=array(), $ampersand='&')
	{
		if($route==='')
			$route=$this->getId().'/'.$this->getAction()->getId();
		else if(strpos($route,'/')===false)
			$route=$this->getId().'/'.$route;
		if($route[0]!=='/' && ($module=$this->getModule())!==null)
			$route=$module->getId().'/'.$route;
		//get param for create url
		$title = FrontendAskModel::model()->findByPk($askId)->title;
		//$alias = StringCommon::str_normalizer($title);
		$params['id'] = $askId;
		$params['alias'] = $title;
		return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
	}

   public function createUrlProductCat($catId, $route='/product/category', $params=array(), $ampersand='&')
   {
        if($route==='')
                $route=$this->getId().'/'.$this->getAction()->getId();
        else if(strpos($route,'/')===false)
                $route=$this->getId().'/'.$route;
        if($route[0]!=='/' && ($module=$this->getModule())!==null)
                $route=$module->getId().'/'.$route;
        //get param for create url
        $title = FrontendShopCategoryModel::model()->findByPk($catId)->name;
        $alias = StringCommon::str_normalizer($title);
        $params['id'] = $catId;
        $params['alias'] = $alias;
        return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
}
    public function createUrlProductDetail($productId, $route='/product/detail', $params=array(), $ampersand='&')
    {
            if($route==='')
                    $route=$this->getId().'/'.$this->getAction()->getId();
            else if(strpos($route,'/')===false)
                    $route=$this->getId().'/'.$route;
            if($route[0]!=='/' && ($module=$this->getModule())!==null)
                    $route=$module->getId().'/'.$route;
            //get param for create url
            $title = FrontendShopProductsModel::model()->findByPk($productId)->name;
            $alias = StringCommon::str_normalizer($title);
            $params['id'] = $productId;
            $params['alias'] = $alias;
            return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
    }
    
    
    
     public function actionFetchTree($id = 'admin') {
        $categories = Menu::model()->findAll(array('order' => 'root,lft'));
        $level = 0;
        foreach ($categories as $n => $category) {
            if ($category->level == $level)
                echo CHtml::closeTag('li') . "\n";
            elseif ($category->level > $level)
                echo CHtml::openTag('ul', array('id' => 'navmenu-v')) . "\n";
            else {
                echo CHtml::closeTag('li') . "\n";
                for ($i = $level - $category->level; $i; $i--) {
                    echo CHtml::closeTag('ul') . "\n";
                    echo CHtml::closeTag('li') . "\n";
                }
            }
            echo CHtml::openTag('li', array('id' => 'node_' . $category->id, 'rel' => $category->name));
            if ($id == 'index')
                echo CHtml::openTag('a', array('href' => $this->createUrl('/products', array('id' => $category->id, 'title' => $category->name))));
            else
                echo CHtml::openTag('a', array('href' => '#'));
            echo CHtml::encode($category->name);
            echo CHtml::closeTag('a');
            $level = $category->level;
        }
        for ($i = $level; $i; $i--) {
            echo CHtml::closeTag('li') . "\n";
            echo CHtml::closeTag('ul') . "\n";
        }
    }

     protected function _loadBreadcrumbs($model, $menu_id = '') {
        $o = Menu::model()->findAll(array('select' => 'id,name', 'condition' => 'lft<' . $model->lft . ' AND rgt>' . $model->rgt, 'order' => 'lft'));
        if (!empty($o)) {
            foreach ($o as $value) {
                $b[] = $value->attributes;
            }
            foreach ($b as $value) {
                $this->breadcrumbs[$value['name']] = $this->createUrl('/products', array('id' => $value['id'], 'title' => $value['name']));
            }
        }
        $p = array(
            'Products' => $this->createUrl('products/random'),
        );
        $this->breadcrumbs = $p + $this->breadcrumbs;
        if (!empty($menu_id))
            $this->breadcrumbs[$model->name] = $this->createUrl('/products', array('id' => $menu_id, 'title' => $model->name));
        else
            array_push($this->breadcrumbs, $model->name);
    }
}